#include "redis_util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/**
 * OpenWrt Redis 开发示例
 * 包含连接管理、数据操作和错误处理
 */

// Redis 连接配置
#define REDIS_HOST "127.0.0.1"
#define REDIS_PORT 6379
#define REDIS_TIMEOUT 5  // 秒

// 创建 Redis 连接
redisContext* create_redis_connection() {
    struct timeval timeout = { REDIS_TIMEOUT, 0 };
    redisContext *conn = redisConnectWithTimeout(REDIS_HOST, REDIS_PORT, timeout);
    
    if (conn == NULL || conn->err) {
        printf("❌ Redis 连接失败: %s\n", conn ? conn->errstr : "无法分配连接");
        return NULL;
    }
    
    printf("✅ Redis 连接成功\n");
    return conn;
}

// 执行 Redis 命令并处理响应
int execute_redis_command(redisContext *conn, const char *format, ...) {
    va_list ap;
    va_start(ap, format);
    redisReply *reply = redisvCommand(conn, format, ap);
    va_end(ap);
    
    if (reply == NULL) {
        printf("❌ 命令执行失败: %s\n", conn->errstr);
        return -1;
    }
    
    int result = 0;
    switch (reply->type) {
        case REDIS_REPLY_ERROR:
            printf("❌ Redis 错误: %s\n", reply->str);
            result = -1;
            break;
        case REDIS_REPLY_INTEGER:
            printf("✅ 命令执行成功，返回值: %lld\n", reply->integer);
            result = reply->integer;
            break;
        case REDIS_REPLY_STRING:
            printf("✅ 命令执行成功，返回值: %s\n", reply->str);
            result = 1;
            break;
        case REDIS_REPLY_STATUS:
            printf("✅ 状态: %s\n", reply->str);
            result = 1;
            break;
        case REDIS_REPLY_NIL:
            printf("⚠️ 键不存在\n");
            result = 0;
            break;
        default:
            printf("📊 响应类型: %d\n", reply->type);
            result = 1;
    }
    
    freeReplyObject(reply);
    return result;
}

// Hash 操作示例
int hash_operations(redisContext *conn) {
    printf("\n=== Hash 操作示例 ===\n");
    
    const char *hash_key = "device:status";
    
    // HSET 设置多个字段
    execute_redis_command(conn, "HSET %s temperature 25.5 humidity 60.0 online 1", hash_key);
    
    // HGET 获取单个字段
    execute_redis_command(conn, "HGET %s temperature", hash_key);
    
    // HGETALL 获取所有字段
    redisReply *reply = redisCommand(conn, "HGETALL %s", hash_key);
    if (reply && reply->type == REDIS_REPLY_ARRAY) {
        printf("📊 Hash 所有字段:\n");
        for (size_t i = 0; i < reply->elements; i += 2) {
            printf("  %s: %s\n", reply->element[i]->str, reply->element[i+1]->str);
        }
    }
    if (reply) freeReplyObject(reply);
    
    return 0;
}

// List 操作示例
int list_operations(redisContext *conn) {
    printf("\n=== List 操作示例 ===\n");
    
    const char *list_key = "device:logs";
    
    // LPUSH 向左添加元素
    execute_redis_command(conn, "LPUSH %s 'Device started' 'Sensor initialized'", list_key);
    
    // LRANGE 获取范围元素
    redisReply *reply = redisCommand(conn, "LRANGE %s 0 -1", list_key);
    if (reply && reply->type == REDIS_REPLY_ARRAY) {
        printf("📊 List 所有元素:\n");
        for (size_t i = 0; i < reply->elements; i++) {
            printf("  [%zu] %s\n", i, reply->element[i]->str);
        }
    }
    if (reply) freeReplyObject(reply);
    
    return 0;
}

// 设置操作示例
int set_operations(redisContext *conn) {
    printf("\n=== Set 操作示例 ===\n");
    
    const char *set_key = "connected:devices";
    
    // SADD 添加元素
    execute_redis_command(conn, "SADD %s device1 device2 device3", set_key);
    
    // SMEMBERS 获取所有元素
    redisReply *reply = redisCommand(conn, "SMEMBERS %s", set_key);
    if (reply && reply->type == REDIS_REPLY_ARRAY) {
        printf("📊 Set 所有元素:\n");
        for (size_t i = 0; i < reply->elements; i++) {
            printf("  • %s\n", reply->element[i]->str);
        }
    }
    if (reply) freeReplyObject(reply);
    
    return 0;
}

// 清理测试数据
void cleanup_test_data(redisContext *conn) {
    printf("\n=== 清理测试数据 ===\n");
    execute_redis_command(conn, "DEL device:status device:logs connected:devices");
}